#include <QtGui>
#include <QDir>
#include "tlocalpathsqlmodel.h"

TLocalPathSqlModel::TLocalPathSqlModel(QObject *parent)
    : QSqlQueryModel(parent)
{
    //sqlText = "select MovieID,Name,LocalPath,FileHash from movies";

    sqlText = "SELECT Episodes.MovieID, movies.Name, Episodes.localpath AS LocalPath, Episodes.FileHash, Episodes.SeasonNum, Episodes.EpisodeNum "
    " FROM movies INNER JOIN Episodes ON movies.MovieID = Episodes.MovieID;"
    " UNION SELECT MovieID ,Name, LocalPath, FileHash,null as SeasonNum,null as EpisodeNum"
    " FROM movies;";
}
void TLocalPathSqlModel::setDb(const QSqlDatabase & db)
{
    clear();
    setQuery(sqlText,db);
    setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
    setHeaderData(1, Qt::Horizontal, QObject::tr("Name"));
    setHeaderData(2, Qt::Horizontal, QObject::tr("Path"));
    setHeaderData(3, Qt::Horizontal, QObject::tr("Hash"));
    setHeaderData(4, Qt::Horizontal, QObject::tr("SeasonNum"));
    setHeaderData(5, Qt::Horizontal, QObject::tr("EpisodeNum"));
}

QVariant TLocalPathSqlModel::data(const QModelIndex &index, int role) const
{
    QVariant value = QSqlQueryModel::data(index, role);
    if (value.isValid() && role == Qt::DisplayRole) {
        if (index.column() == 0)
            return value.toString().prepend("#");
        else if (index.column() == 2)
            return value.toString().toUpper();
    }
    if (role == Qt::TextColorRole && index.column() == 1)
        return qVariantFromValue(QColor(Qt::blue));
    if (role == Qt::TextColorRole && index.column() == 2){
        QVariant valuePath = QSqlQueryModel::data(index, Qt::DisplayRole);
        if(valuePath.isValid()){
            QDir dir;
            QString n = dir.absoluteFilePath(valuePath.toString());
            QFile file(dir.absoluteFilePath(valuePath.toString()));
            if(file.exists())
                return qVariantFromValue(QColor(Qt::blue));
            else
                return qVariantFromValue(QColor(Qt::red));
        }
    }
    return value;
}
